package com.lyc.service.impl;

import com.lyc.dao.ColorMapper;
import com.lyc.dao.ProductMapper;
import com.lyc.dao.SizeMapper;
import com.lyc.entity.Color;
import com.lyc.entity.Product;
import com.lyc.entity.vo.PageBean;
import com.lyc.service.IColorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ColorServiceImpl implements IColorService {

    @Autowired
    private ColorMapper colorMapper;

    @Autowired
    private SizeMapper sizeMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public PageBean<Color> selectByPage(Integer currentPage, int colorPageSize) {
        PageBean<Color> page = new PageBean<>();
        page.setCurrentPage(currentPage);
        page.setPageSize(colorPageSize);
        page.setTotalCount(colorMapper.selectAllCount());
        page.setData(colorMapper.selectByPage(page.getStart(),page.getPageSize()));
        page.setTotalPage((int)Math.ceil((double)(page.getTotalCount())/page.getPageSize()));
        return page;
    }

    @Override
    public void addColor(Color color) {
        colorMapper.insertSelective(color);
    }

    @Override
    public Color selectByColorId(Integer colorId) {
        return colorMapper.selectByPrimaryKey(colorId);
    }

    @Override
    public void updateColor(Color color) {
        colorMapper.updateByPrimaryKeySelective(color);
    }

    @Override
    public void deleteColorByColorId(Integer colorId) {
        //删除颜色前删除该颜色对应的商品信息
        colorMapper.deleteProductByColorId(colorId);
        colorMapper.deleteByPrimaryKey(colorId);
    }

    @Override
    public List<Color> getAll() {
        return colorMapper.selectAll();
    }

    @Override
    public void operateColor(List<Integer> ids, Integer pid) {
        //获取该商品的所有颜色
        Product product = productMapper.selectByPrimaryKey(pid);
        //删除该商品的所有尺码/颜色
        sizeMapper.deleteByPid(pid);
        ///添加该商品原有的尺码
        sizeMapper.insertBatchBySizes(product.getSizes(),pid);
        //添加商品新增颜色
        colorMapper.insertBatchByIds(ids,pid);
    }
}
